package com.yyfax.ph.home.recommendloan.creditinfo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.bumptech.glide.Glide;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.ph.R;
import com.yyfax.ph.base.PermissionFragment;
import com.yyfax.ph.base.dialog.DialogBase;
import com.yyfax.ph.common.imageselector.activity.PhotoSelectorActivity;
import com.yyfax.ph.common.imageselector.activity.PhotoViewActivity;
import com.yyfax.ph.common.imageselector.bean.ImageBean;
import com.yyfax.ph.common.utils.Constants;
import com.yyfax.ph.common.widgets.AllDisplayGridView;
import com.yyfax.ph.home.imageupload.ImageAdapter;
import com.yyfax.ph.home.imageupload.ImageSelectArguments;
import com.yyfax.ph.home.imageupload.ImageUploadArguments;
import com.yyfax.ph.home.imageupload.UploadImagePresenter;

import java.util.ArrayList;
import java.util.List;

/**
 * 有征信报告
 * Created by ying_he on 2017/11/3.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */

public class HasCreditPaperFragment extends PermissionFragment implements UploadImagePresenter.View,
		ImageAdapter.ChooseUploadListener, ChoosePictureDialog.ChoosePictureListener {
	private static final String TAG = HasCreditPaperFragment.class.getSimpleName();

	private static final int LOADER_ID = 901;
	private static final int REQUEST_IMAGE = 0x0001;
	private static final String BUNDLE_KEY_IMAGE_BEANS = "bundle_key_image_beans";

	@BindView(R.id.upload_image_grid_view)
	AllDisplayGridView mUploadImageGridView;
	@BindView(R.id.upload_layout)
	TextView mUploadLayout;

	private ImageAdapter mImageAdapter;
	private UploadImagePresenter mPresenter;
	private List<String> mUploadImage = new ArrayList<>();//逐张上传
	boolean mOnActivityResult = false; //是否从onActivityResult返回来
	private boolean mUploading = false;//是否正在上传
	private ImageUploadArguments mArguments;//上传图片所传参数
	Unbinder mUnBinder;
	private UploadCreditPaperFragment.ExtraParamsToUploadCredit mExtraParamsToUploadCredit;
	private int mPermissionRequestCodeExternalStorage = DEFAULT_PERMISSION_REQUEST_CODE_EXTERNAL_STORAGE;
	private boolean mHasShowedExampleDialog = false;

	public static HasCreditPaperFragment newInstance(UploadCreditPaperFragment.ExtraParamsToUploadCredit extraParamsToUploadCredit){
		HasCreditPaperFragment fragment = new HasCreditPaperFragment();
		Bundle args = new Bundle();
		args.putParcelable(UploadCreditPaperFragment.BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT, extraParamsToUploadCredit);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		getActivity().getSupportLoaderManager().initLoader(LOADER_ID, null, this);
	}

	@Override
	public void onDetach() {
		super.onDetach();
		getActivity().getSupportLoaderManager().destroyLoader(LOADER_ID);
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_has_credit_paper, null);
		mUnBinder = ButterKnife.bind(this, view);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initData(savedInstanceState);
	}

	private void initData(Bundle savedInstanceState){
		mImageAdapter = new ImageAdapter(getActivity(), this, true);
		mUploadImageGridView.setAdapter(mImageAdapter);
		mUploadImageGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {//停止滑动状态
					Glide.get(getActivity()).clearMemory();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

			}
		});

		if (savedInstanceState != null){
			readBundle(savedInstanceState);
			if (mArguments != null) {
				mImageAdapter.addData(mArguments.imageBeans);
				mImageAdapter.notifyDataSetChanged();
			}
		}else {
			mArguments = new ImageUploadArguments();
			mArguments.imageType = Constants.IMAGE_TYPE_CREDIT;
			mArguments.title = getResources().getString(R.string.upload_credit_report);
			mArguments.remainCount = Constants.MAX_IMAGE_COUNT_DEFAULT;
			mArguments.maxCount = Constants.MAX_IMAGE_COUNT_DEFAULT;
			mExtraParamsToUploadCredit = getArguments().getParcelable(UploadCreditPaperFragment.BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT);
		}

		if (mExtraParamsToUploadCredit != null && (mExtraParamsToUploadCredit.bizType == UploadCreditPaperFragment.BIZ_TYPE_HAS_CREDIT_SUPPLEMENT_UPLOAD
				||mExtraParamsToUploadCredit.bizType == UploadCreditPaperFragment.BIZ_TYPE_NO_CREDIT_SUPPLEMENT_UPLOAD) ){
			mUploadLayout.setVisibility(View.GONE);
		}
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		mUnBinder.unbind();
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(getActivity(), new UploadImagePresenter.Generator());
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		mPresenter = (UploadImagePresenter) data;
		mPresenter.attach(this);
	}

	@OnClick({R.id.upload_layout})
	public void onClicked(View view){
		confirm();
	}

	public void confirm() {
		if (mImageAdapter.getSuccessBeanList().size() <= 0){
			showToast(R.string.should_select_credit_paper_pic);
			return;
		}

		if (mImageAdapter.isUploading()){
			showToast(R.string.pic_is_uploading);
			return;
		}

		int failSize = mImageAdapter.getFailPathList().size();
		if (failSize > 0) {
			new DialogBase(getActivity(), getString(R.string.you_have_failed_uploded_failed_imags_strs, String.valueOf(failSize)),null,
					getResources().getString(R.string.give_up_uplaod),
					getResources().getString(R.string.reupload),
					new DialogBase.BottomTwoClickListener() {
						@Override
						public void onCancelClick(DialogBase dialog) {
							dialog.dismiss();
							submitCredit();
						}

						@Override
						public void onConfirmClick(DialogBase dialog) {
							// TODO: 2017/5/11 待确认
							uploadImages();
							dialog.dismiss();
						}
					}).show();
		} else {
			submitCredit();
		}
	}

	/**
	 * 提交征信报告上传
	 */
	public void submitCredit(){
		UploadCreditPaperFragment.UploadCreditPaperEvent uploadCreditPaperEvent = new UploadCreditPaperFragment.UploadCreditPaperEvent();
		uploadCreditPaperEvent.bizType = mExtraParamsToUploadCredit.bizType;
		uploadCreditPaperEvent.rcmId = mExtraParamsToUploadCredit.rcmId;
		uploadCreditPaperEvent.imageIds = mImageAdapter.getSuccessImageIdList();
		if (mExtraParamsToUploadCredit.bizType == UploadCreditPaperFragment.BIZ_TYPE_HAS_CREDIT_SUPPLEMENT_UPLOAD){
			uploadCreditPaperEvent.flag = "";
		}

		EventAgent.post(uploadCreditPaperEvent);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		mOnActivityResult = true;
		if (resultCode == getActivity().RESULT_OK) {
			switch (requestCode) {
				case REQUEST_IMAGE:
					ArrayList<ImageBean> newImageBeans = data.getParcelableArrayListExtra(PhotoSelectorActivity.EXTRA_COMPRESSED_BEANS);
					mImageAdapter.removeAll();
					if (null == newImageBeans || newImageBeans.size() == 0) {//如果没有数据, 则清空当前adapter, 并返回
						mArguments.imageBeans.clear();
						mImageAdapter.notifyDataSetChanged();
						return;
					}
					for (ImageBean bean : newImageBeans) {
						if (mArguments.imageBeans.contains(bean)) {
							bean.status = ImageBean.STATUS_SUCCESS;
							bean.imageId = mArguments.imageBeans.get(mArguments.imageBeans.indexOf(bean)).imageId;
						}
					}
					mArguments.imageBeans.clear();
					mArguments.imageBeans.addAll(newImageBeans);
					mImageAdapter.addData(mArguments.imageBeans);
					mImageAdapter.notifyDataSetChanged();
					uploadImages();
					break;
				default:
					break;
			}
		}
	}

	private void uploadImages() {
		List<String> uploadList = getUploadImages();
		if (uploadList.size() == 0) {
			mUploading = false;
			return;
		}
		mUploading = true;
		mPresenter.uploadImages(getUploadImages(), getImageType());
	}

	private void uploadSingleImage() {
		if (mUploadImage.size() > 0) {
			String filePath = mUploadImage.get(0);
			mPresenter.uploadImage(filePath, getImageType());
		}
	}

	public String getImageType() {
		return mArguments.imageType;
	}

	/**
	 * 获取待上传的图片(已选择的图片-已上传的图片)
	 *
	 * @return
	 */
	public List<String> getUploadImages() {//获取待上传的图片(已选择的图片-已上传的图片)
		mUploadImage.clear();
		List<String> files = mImageAdapter.getNeedUploadPath();
		mUploadImage.addAll(files);
		mImageAdapter.notifyDataSetChanged();
		return files;
	}

	@Override
	protected void permissionsAllGrantedSuccess(int requestCode) {
		if (requestCode == mPermissionRequestCodeExternalStorage){
			choosePictures();
		}
	}

	@Override
	public void onTakePicture() {

	}

	@Override
	public void onChoosePictures() {
		choosePictures();
	}

	@Override
	public void onAddClick() {
		if (!mHasShowedExampleDialog){
			new ChoosePictureDialog(getActivity(), R.drawable.ic_example_credit_paper, this, true).show();
			mHasShowedExampleDialog = true;
			return;
		}

		choosePictures();
	}

	private void choosePictures(){
		if (!hasWriteStoragePermission(mPermissionRequestCodeExternalStorage)) {
			return;
		}
		if (mUploading) {
			showToast(R.string.exit_toast_uploading);
			return;
		}
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			ImageSelectArguments arguments = new ImageSelectArguments();
			arguments.showCamera = true;
			arguments.selectMode = PhotoSelectorActivity.SELECT_MODE_MULTI;
			arguments.remainCount = mArguments.remainCount;
			arguments.maxCount = mArguments.maxCount;
			arguments.selectedImages = mImageAdapter.getOriginalPathList();
			arguments.compressedImages = (ArrayList<ImageBean>) mImageAdapter.getDataSet();
			PhotoSelectorActivity.startForResult(getActivity(), arguments, REQUEST_IMAGE);
		}
	}

	@Override
	public void onDelClick(String path) {
		if (mUploading) {
			showToast(R.string.exit_toast_uploading);
			return;
		}
		ImageBean delBean = new ImageBean(path, path);
		mImageAdapter.getDataSet().remove(delBean);
		mArguments.imageBeans.clear();
		mArguments.imageBeans.addAll(mImageAdapter.getDataSet());
		mImageAdapter.notifyDataSetChanged();
	}

	@Override
	public void onReClickUpload(String path) {
		if (mUploading) {
			showToast(R.string.exit_toast_uploading);
			return;
		}
		uploadImages();
	}

	@Override
	public void onReviewClick(int position) {
		if (mUploading) {
			showToast(R.string.exit_toast_uploading);
			return;
		}
		ArrayList<String> picUrls = new ArrayList<>();
		picUrls.addAll(mImageAdapter.getPathList());
		PhotoViewActivity.start(getActivity(), picUrls, position, false);
	}

	@Override
	public void onUploadImage(String filePath, String fileName, String imageId) {
		mUploadImage.remove(filePath);
		mImageAdapter.changeStatus(filePath, ImageBean.STATUS_SUCCESS, imageId);
		mArguments.imageBeans.clear();
		mArguments.imageBeans.addAll(mImageAdapter.getDataSet());
		mImageAdapter.notifyDataSetChanged();
		if (mUploadImage.size() == 0) {
			mUploading = false;
		} else {
			uploadSingleImage();
		}
	}

	@Override
	public void onUploadImageFailure(String filePath, String tips) {
		mUploadImage.remove(filePath);
		mImageAdapter.changeStatus(filePath, ImageBean.STATUS_FAIL, "");
		mArguments.imageBeans.clear();
		mArguments.imageBeans.addAll(mImageAdapter.getDataSet());
		mImageAdapter.notifyDataSetChanged();
		if (mUploadImage.size() == 0) {
			mUploading = false;
		} else {
			uploadSingleImage();
		}
	}

	@Override
	public void onUploadImageCancel(String filePath, String tips) {
		if (mUploadImage.contains(filePath)) {
			mImageAdapter.changeStatus(filePath, ImageBean.STATUS_FAIL, "");
			mArguments.imageBeans.clear();
			mArguments.imageBeans.addAll(mImageAdapter.getDataSet());
			mImageAdapter.notifyDataSetChanged();
			mUploadImage.remove(filePath);
			if (mUploadImage.size() == 0) {
				mUploading = false;
			} else {
				uploadSingleImage();
			}
		}
	}

	private void readBundle(Bundle bundle){
		mArguments = bundle.getParcelable(BUNDLE_KEY_IMAGE_BEANS);
		mExtraParamsToUploadCredit = bundle.getParcelable(UploadCreditPaperFragment.BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (mArguments != null){
			for (int i = 0; i < mArguments.imageBeans.size(); i++){
				ImageBean imageBean = mArguments.imageBeans.get(i);
				if (ImageBean.STATUS_ING == imageBean.status) {
					imageBean.status = ImageBean.STATUS_FAIL;
				}
			}
		}
		outState.putParcelable(BUNDLE_KEY_IMAGE_BEANS, mArguments);
		outState.putParcelable(UploadCreditPaperFragment.BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT, mExtraParamsToUploadCredit);
	}
}
